package com.aiton.bamin.bamindaijiadrier.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.utils.ACache;
import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.utils.UILUtils;
import com.aiton.administrator.shane_library.shane.widget.CircleImageView;
import com.aiton.bamin.bamindaijiadrier.R;
import com.aiton.bamin.bamindaijiadrier.constant.Constant;
import com.aiton.bamin.bamindaijiadrier.model.User;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import cz.msebera.android.httpclient.Header;

public class MineActivity extends ZjbBaseActivity implements View.OnClickListener {

    private CircleImageView mImg_Avatar;
    private TextView mTv_Name;
    private TextView mTv_User_Phone;
    private ACache aCache;
    private User mUser;
    private User.DatasBean datas;
    private String imgUrl;
    private String mImage;
    private String mPhoneNum;
    private String name;
    private TextView mTv_User_emergency;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    Constant.PERMISSION.CAMERA);//自定义的code
        }
        init();
    }
    @Override
    protected void initData() {
    }
    @Override
    protected void initViews() {
        User.DatasBean datas = mUser.getDatas();
        if (datas != null) {
            mImage = datas.getImage();
            name = datas.getName();
            String urgentPhone = datas.getUrgentPhone();
            String phone = datas.getPhone();
            Log.e("MineActivity", "用户信息: --->>" +name + "-----" + phone +"----" +  urgentPhone + "-----" + mImage);

            if (mImage != null) {
                Log.e("checkLogin", "图片URL" + mImage);
                UILUtils.displayImageNoAnim(mImage, mImg_Avatar);
            } else {
                mImg_Avatar.setImageResource(R.mipmap.ic_avatar);
            }
            if (name != null && !TextUtils.isEmpty(name)) {
                mTv_Name.setText(name);
            }
            if (phone != null && !TextUtils.isEmpty(phone)) {
                mTv_User_Phone.setText(phone);
            }
            if (urgentPhone != null && !TextUtils.isEmpty(urgentPhone)) {
                mTv_User_emergency.setText(urgentPhone);
            }

        }
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageView_back).setOnClickListener(this);
//        findViewById(R.id.rela_user_avatar).setOnClickListener(this);
//        findViewById(R.id.rela_user_name).setOnClickListener(this);
//        findViewById(R.id.rela_user_emergency).setOnClickListener(this);
    }

    @Override
    protected void initSP() {
        aCache = ACache.get(this);
        mUser = (User) aCache.getAsObject(Constant.ACACHE.USER);
        if (mUser != null) {
            datas = mUser.getDatas();
            imgUrl = datas.getImage();
            Log.e("MineActivity", "ID: --->>" + mUser.getDatas().getId());
        }
    }

    @Override
    protected void initIntent() {

    }

    @Override
    protected void findID() {
        mImg_Avatar = (CircleImageView) findViewById(R.id.imageView_touXiang);
        mTv_Name = (TextView) findViewById(R.id.tv_user_name);
        mTv_User_Phone = (TextView) findViewById(R.id.tv_user_phone);
        mTv_User_emergency = (TextView) findViewById(R.id.tv_user_emergency);

    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        String userName = mTv_Name.getText().toString().trim();
        String emergency = mTv_User_emergency.getText().toString().trim();

        String image = mUser.getDatas().getImage();
        if (userName.equals("请填写姓名")) {
            userName = "";
        }
        if (emergency.equals("请填写紧急联系人")) {
            emergency = "";
        }
        switch (v.getId()) {
            case R.id.imageView_back:
                intent.putExtra(Constant.INTENT_KEY.USER_NAME, userName);
                intent.putExtra(Constant.INTENT_KEY.USER_AVATAR, image);
                setResult(Constant.REQUEST_RESULT_CODE.USER_INFO, intent);
                finishTo();
                break;

            case R.id.rela_user_name:
                intent.setClass(this, ChangeNameActivity.class);
                intent.putExtra(Constant.INTENT_KEY.CHANGE_NAME, mTv_Name.getText().toString());
                intent.putExtra(Constant.INTENT_KEY.ADD_INFO_TYPE, Constant.TYPE.CHANGE_NAME);

                startActivityForResultTo(intent, Constant.REQUEST_RESULT_CODE.CHANGE_NAEM);

                break;
            case R.id.rela_user_emergency://紧急联系人
                intent.setClass(this, ChangeNameActivity.class);
                intent.putExtra(Constant.INTENT_KEY.EMERGENCY, emergency);
                intent.putExtra(Constant.INTENT_KEY.ADD_INFO_TYPE, Constant.TYPE.EMERGENCY);
                startActivityForResultTo(intent, Constant.REQUEST_RESULT_CODE.EMERGENCY);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constant.REQUEST_RESULT_CODE.CHANGE_NAEM && resultCode == Constant.REQUEST_RESULT_CODE.CHANGE_NAEM) {

            String name = data.getStringExtra(Constant.INTENT_KEY.CHANGE_NAME);
            Log.e("MineActivity", "name: --->>" + name);
            mTv_Name.setText(name);

        }
    }

//    /**
//     * 上传图片
//     *
//     * @param uploadFile
//     */
//    public void postFile(Uri uploadFile) {
//        String path = uploadFile.getPath();
//        Log.e("postFile", "path" + path);
//        File file = new File(path);
//
//        String actionUrl = Constant.Url.CUSTOMERIMAGE;
//        if (file.exists() && file.length() > 0) {
//            RequestParams params = new RequestParams();
//            params.put("driver_id", mUser.getDatas().getId());
//            Log.e("postFile", "用户ID" + mUser.getDatas().getId());
//            try {
//                params.put("data", file);
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
//            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
//            asyncHttpClient.post(actionUrl, params, new AsyncHttpResponseHandler() {
//
//                @Override
//                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//                    Log.e("onSuccess: ", "---> " + new String(responseBody));
//                    try {
//                        String imgUrl = new String(responseBody);
//                        datas.setImage(imgUrl);
//                        mUser.setDatas(datas);
//                        aCache.clear();
//                        aCache.put(Constant.ACACHE.USER, mUser, 30 * ACache.TIME_DAY);
//
//                        mUser = (User) aCache.getAsObject(Constant.ACACHE.USER);
//                        sendUserBroadcase();
//
//                        Log.e("MineActivity", "图片imgUrl:>>" + imgUrl);
//                        Toast.makeText(MineActivity.this, "设置新的头像成功", Toast.LENGTH_SHORT).show();
//
//                    } catch (Exception e) {
//
//                    }
//                }
//
//                @Override
//                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//                    Log.e("onFailure", "失败");
//                }
//            });
//        } else {
//            Toast.makeText(this, "文件不存在", Toast.LENGTH_LONG).show();
//        }
//        ImageLoader.getInstance().clearDiskCache();
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        pushUserInfo();

    }

    /**
     * 上传用户信息
     */
    private void pushUserInfo() {
        String name = mTv_Name.getText().toString().trim();
        String emergency = mTv_User_emergency.getText().toString().trim();
        boolean hasChange = false;
        Log.e("MineActivity", "pushUserInfo: --->>" + mUser.getDatas().getName());

        Log.e("MineActivity", "pushUserInfo: --->>" + (name.equals("请填写姓名") || name.equals(mUser.getDatas().getName())));

        if (!(name.equals("请填写姓名") || name.equals(mUser.getDatas().getName()))) {
            hasChange = true;
        }
        if (!(emergency.equals("请填写紧急联系人"))) {
            hasChange = true;
        }
        if (hasChange) {

            String url = Constant.Url.USER_INFO;
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            params.put("id", mUser.getDatas().getId());
            params.put("name", name);
            params.put("phone", mUser.getDatas().getPhone());
            asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    String s = new String(responseBody);
                    try {
                        mUser = GsonUtils.parseJSON(s, User.class);
                        if (mUser.getStatus() == 0) {

                            aCache.clear();
                            aCache.put(Constant.ACACHE.USER, mUser, 30 * ACache.TIME_DAY);
                            mUser = (User) aCache.getAsObject(Constant.ACACHE.USER);
                            sendUserBroadcase();
                        }
                    } catch (Exception e) {

                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Toast.makeText(MineActivity.this, "用户信息保存失败", Toast.LENGTH_SHORT).show();
                    Log.e("MineActivity", "用户信息保存失败");
                }
            });
        }
    }

    private void sendUserBroadcase() {
        Intent intent = new Intent(Constant.BROADCASTCODE.USER);
        intent.putExtra(Constant.INTENT_KEY.USER, mUser);
        sendBroadcast(intent);
    }
}
